<?php

namespace App\Http\Controllers\Api;

use App\Enrollment;
use App\Event;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

class EnrollController extends Controller
{
    public function create(Request $request,Event $event){
        $validate = $this->validate($request,[
            'firstname'=>'required',
            'lastname'=>'required',
            'phone'=>'required',
            'email'=>'required|email'
        ]);

        $enrollment =Enrollment::where('event_id',$event->id)->where('email',$validate['email'])->first();
        if (!empty($enrollment)) return $this->error_422('This email address has already been token');

        $enrollment = new Enrollment($validate);
        $enrollment->event_id = $event->id;
        $enrollment->save();

        return $this->success(['id'=>$enrollment->id]);
    }
    public function events($email,$phone){
        $enrollments = Enrollment::where('email',$email)
            ->where('phone',$phone)
            ->with(['event'=>function($query){
                $query->select(['id','name','photo','date']);
            }])
            ->get()
            ->makeHidden(['email','phone','event_id'])
            ->each(function ($item){
                $item->event->makeHidden(['id']);
            });

        if ($enrollments->count() <= 0) throw  new ModelNotFoundException();

        return $this->success($enrollments);
    }
}
